package com.yic.module.device.controller.admin.receive;

import cn.hutool.core.util.ObjectUtil;
import com.yic.module.base.api.center.CenterApi;
import com.yic.module.base.api.center.dto.CenterRespDTO;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.device.dal.dataobject.device.DeviceDO;
import com.yic.module.device.service.device.DeviceService;
import com.yic.module.system.api.dept.dto.DeptRespDTO;
import com.yic.module.system.api.user.AdminUserApi;
import com.yic.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.device.controller.admin.receive.vo.*;
import com.yic.module.device.dal.dataobject.receive.ReceiveDO;
import com.yic.module.device.convert.receive.ReceiveConvert;
import com.yic.module.device.service.receive.ReceiveService;

@Tag(name = "管理后台 - 领用申请")
@RestController
@RequestMapping("/device/receive")
@Validated
public class ReceiveController {

    @Resource
    private ReceiveService receiveService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeviceService deviceService;
    @Resource
    private FactoryApi factoryApi;
    @Resource
    private CenterApi centerApi;

    @PostMapping("/create")
    @Operation(summary = "创建领用申请")
    @PreAuthorize("@ss.hasPermission('device:receive:create')")
    public CommonResult<Long> createReceive(@Valid @RequestBody ReceiveCreateReqVO createReqVO) {
        return success(receiveService.createReceive(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新领用申请")
    @PreAuthorize("@ss.hasPermission('device:receive:update')")
    public CommonResult<Boolean> updateReceive(@Valid @RequestBody ReceiveUpdateReqVO updateReqVO) {
        receiveService.updateReceive(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除领用申请")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('device:receive:delete')")
    public CommonResult<Boolean> deleteReceive(@RequestParam("id") Long id) {
        receiveService.deleteReceive(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得领用申请")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('device:receive:query')")
    public CommonResult<ReceiveRespVO> getReceive(@RequestParam("id") Long id) {
        ReceiveDO receive = receiveService.getReceive(id);
        return success(ReceiveConvert.INSTANCE.convert(receive));
    }

    @GetMapping("/list")
    @Operation(summary = "获得领用申请列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('device:receive:query')")
    public CommonResult<List<ReceiveRespVO>> getReceiveList(@RequestParam("ids") Collection<Long> ids) {
        List<ReceiveDO> list = receiveService.getReceiveList(ids);
        return success(ReceiveConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得领用申请分页")
    @PreAuthorize("@ss.hasPermission('device:receive:query')")
    public CommonResult<PageResult<ReceiveRespVO>> getReceivePage(@Valid ReceivePageReqVO pageVO) {
        PageResult<ReceiveDO> pageResult = receiveService.getReceivePage(pageVO);
        PageResult<ReceiveRespVO> resp = ReceiveConvert.INSTANCE.convertPage(pageResult);
        resp.getList().forEach(item -> {
            // 封装用户
            AdminUserRespDTO user = adminUserApi.getUser(item.getUserId());
            if (ObjectUtil.isNotEmpty(user)) {
                item.setUserName(user.getNickname());
            }
            // 封装设备
            DeviceDO device = deviceService.get(item.getDeviceId());
            if (ObjectUtil.isNotEmpty(device)) {
                item.setDeviceName(device.getName());
                item.setDeviceCode(device.getCode());
            }
            // 封装工作中心
            CenterRespDTO center = centerApi.getCenter(item.getCenterId());
            if (ObjectUtil.isNotEmpty(center)) {
                item.setCenterName(center.getName());
            }
            // 封装工厂
            FactoryRespDTO factory = factoryApi.getFactory(item.getFactoryId());
            if (ObjectUtil.isNotEmpty(factory)) {
                item.setFactoryName(factory.getName());
            }
        });
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出领用申请 Excel")
    @PreAuthorize("@ss.hasPermission('device:receive:export')")
    @OperateLog(type = EXPORT)
    public void exportReceiveExcel(@Valid ReceiveExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ReceiveDO> list = receiveService.getReceiveList(exportReqVO);
        // 导出 Excel
        List<ReceiveExcelVO> datas = ReceiveConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "领用申请.xls", "数据", ReceiveExcelVO.class, datas);
    }

    @PutMapping("/approve")
    @Operation(summary = "审批领用申请")
    @PreAuthorize("@ss.hasPermission('device:receive:approve')")
    public CommonResult<Boolean> approveReceive(@RequestParam("id") Long id){
        receiveService.approveReceive(id);
        return success(true);
    }

    @PutMapping("/cancel")
    @Operation(summary = "撤审")
    @PreAuthorize("@ss.hasPermission('device:receive:approve')")
    public CommonResult<Boolean> cancelReceive(@RequestParam("id") Long id){
        receiveService.cancelReceive(id);
        return success(true);
    }

}
